package com.pi.pro.xcmg.am.was.fac;

import com.pi.pro.xcmg.am.was.fac.service.LicenseService;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 *  .
 */
//@Component
public class LicenseInterceptor implements HandlerInterceptor {

    private RedissonClient redissonClient;
    private LicenseService licenseService;

    public LicenseInterceptor(RedissonClient redissonClient, LicenseService licenseService){
        this.redissonClient=redissonClient;
        this.licenseService=licenseService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 请求处理前的操作
        //System.out.println("Pre-handle method is called");
        String key = "LIC:XCMG:WH101//EXP";
        RBucket<String> bucket=null;
        String exptime=null;
        Date expdate=null;
        String url=null;
        try{
            bucket=this.redissonClient.getBucket(key);
            if (bucket!=null){
                exptime=bucket.get();
                if (exptime!=null){
                    url=request.getRequestURL().toString();
                    if ((url.endsWith(":8060/"))|| (url.indexOf("8060/login")>0) || (url.endsWith(".css"))){
                        return true;
                    }
                    if (!this.licenseService.isLicenseNotExpired(exptime)){
                        response.addHeader("applicationTitle", "登录失效");
                        return false;
                    }
                    return true;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return true; // 如果返回false，则会中断后续处理
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求处理后，视图渲染前的操作
        System.out.println("Post-handle method is called");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完全结束后执行
        System.out.println("After-completion method is called");
    }
}
